<template>
  <view class="vip-container">
    <!-- 顶部栏 -->
    <view class="top-bar">
      <text class="title">会员中心</text>
      <view class="record-btn" @click="goToRecord">
        <text>消费记录</text>
      </view>
    </view>

    <!-- 用户欢乐豆信息 -->
    <view class="user-beans">
      <text class="label">当前欢乐豆：</text>
      <text class="value">{{userBeans}}豆</text>
    </view>

    <!-- 会员卡片列表 -->
    <view class="vip-list">
      <!-- 兑换会员卡片 -->
      <view class="card-group">
        <view class="group-header">
          <text class="title">兑换会员</text>
          <text class="tag">兑换</text>
        </view>
        <view class="card-wrapper">
          <view class="vip-card exchange" v-for="item in exchangeList" :key="item.id">
            <view class="card-icon">
              <image src="/static/vip/icon-beans.png" mode="aspectFit" />
            </view>
            <view class="card-content">
              <view class="duration">{{item.memberDuration}}天</view>
              <view class="price">{{item.beans}}欢乐豆</view>
              <view class="stock">库存：{{item.munber}}</view>
              <button 
                class="exchange-btn"
                :class="{'disabled': item.munber <= 0}"
                @click="handleExchange(item)"
              >立即兑换</button>
            </view>
          </view>
        </view>
      </view>

      <!-- 购买会员卡片 -->
      <view class="card-group">
        <view class="group-header">
          <text class="title">购买会员</text>
          <text class="tag buy">购买</text>
        </view>
        <view class="card-wrapper">
          <view class="vip-card purchase" v-for="item in purchaseList" :key="item.id">
            <view class="card-icon">
              <image src="/static/vip/icon-crown.png" mode="aspectFit" />
            </view>
            <view class="card-content">
              <view class="duration">{{item.memberDuration}}天</view>
              <view class="price">¥{{item.price}}</view>
              <button class="purchase-btn" @click="handlePurchase(item)">立即购买</button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 会员权益 -->
    <view class="vip-benefits">
      <view class="benefits-header">
        <text class="title">会员权益</text>
      </view>
      <view class="benefits-list">
        <view class="benefit-item" v-for="(benefit, index) in benefits" :key="index">
          <image class="icon" :src="benefit.icon" mode="aspectFit"></image>
          <text class="text">{{benefit.text}}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userId: 1, // 开发测试阶段固定userId为1
      userBeans: 0,
      exchangeList: [], // 兑换列表
      purchaseList: [], // 购买列表
      loading: false,
      benefits: [
        {
          icon: '/static/vip/icon-badge.png',
          text: '专属身份标识'
        },
        {
          icon: '/static/vip/icon-beans.png',
          text: '每日签到双倍欢乐豆'
        },
        {
          icon: '/static/vip/icon-priority.png',
          text: '专属活动优先参与'
        }
      ]
    }
  },
  async created() {
    await this.getMemberInfo()
  },
  
  onShow() {
    this.getMemberInfo()
  },

  methods: {
    // 获取会员信息和兑换列表
    async getMemberInfo() {
      try {
        const res = await uni.request({
          url: `http://localhost:9224/member/info`,
          method: 'GET',
          data: {
            userId: this.userId
          }
        })
        
        console.log('获取到的会员信息：', res.data)
        
        if (res.data.code === 200) {
          const data = res.data.data
          console.log('解析后的数据：', data)
          this.userBeans = data.beans || 0
          this.exchangeList = data.exchangeList || []
          this.purchaseList = data.purchaseList || []
          
          console.log('兑换列表：', this.exchangeList)
          console.log('购买列表：', this.purchaseList)
        } else {
          uni.showToast({
            title: res.data.msg || '获取数据失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取会员信息失败：', error)
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        })
      }
    },

    // 跳转到消费记录
    goToRecord() {
      uni.navigateTo({
        url: '/pages/sign/record'
      })
    },

    // 兑换会员
    async handleExchange(item) {
      if (this.loading) return
      
      console.log('准备兑换的会员：', item)
      
      if (this.userBeans < parseInt(item.beans)) {
        uni.showToast({
          title: '欢乐豆不足',
          icon: 'none'
        })
        return
      }

      if (parseInt(item.munber) <= 0) {
        uni.showToast({
          title: '库存不足',
          icon: 'none'
        })
        return
      }

      this.loading = true
      try {
        const res = await uni.request({
          url: 'http://localhost:9224/member/purchase',
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          data: {
            userId: this.userId,
            typeId: item.id,
            manner: 0 // 0表示欢乐豆兑换
          }
        })

        console.log('兑换结果：', res.data)

        if (res.data.code === 200) {
          uni.showToast({
            title: '兑换成功',
            icon: 'success'
          })
          // 刷新数据
          await this.getMemberInfo()
        } else {
          uni.showToast({
            title: res.data.msg || '兑换失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('兑换失败：', error)
        uni.showToast({
          title: '兑换失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 购买会员
    async handlePurchase(item) {
      // if (this.loading) return

      console.log('准备购买的会员：', item)

      // this.loading = true
      try {
        // 注释或移除原有的购买接口调用
        // const res = await uni.request({
        //   url: 'http://localhost:9224/member/purchase',
        //   method: 'POST',
        //   header: {
        //     'content-type': 'application/json'
        //   },
        //   data: {
        //     userId: this.userId,
        //     typeId: item.id,
        //     manner: 1 // 1表示购买
        //   }
        // })

        // console.log('购买结果：', res.data)

        // if (res.data.code === 200) {
        //   uni.showToast({
        //     title: '购买成功',
        //     icon: 'success'
        //   })
        //   // 刷新数据
        //   await this.getMemberInfo()
        // } else {
        //   uni.showToast({
        //     title: res.data.msg || '购买失败',
        //     icon: 'none'
        //   })
        // }

        // 修改为跳转到支付页面，并传递参数
        uni.navigateTo({
          url: `/pages/sign/payment?vipType=${item.memberDuration}天&amount=${item.price}`
        });

      } catch (error) {
        console.error('跳转支付页面失败：', error)
        uni.showToast({
          title: '跳转支付失败',
          icon: 'none'
        })
      } finally {
        // this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.vip-container {
  min-height: 100vh;
  background: #fff;
  padding: 32rpx 20rpx;
  box-sizing: border-box;
  
  .top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 0 36rpx 0;
    margin-bottom: 0;
    
    .title {
      font-size: 38rpx;
      color: #222;
      font-weight: bold;
      letter-spacing: 2rpx;
    }
    
    .record-btn {
      padding: 10rpx 32rpx;
      background: #e8f5e9;
      border-radius: 30rpx;
      
      text {
        font-size: 28rpx;
        color: #07c160;
        font-weight: 500;
      }
    }
  }
  
  .user-beans {
    background: linear-gradient(90deg, #e0ffe6 0%, #f8fff8 100%);
    padding: 36rpx 30rpx;
    border-radius: 18rpx;
    margin-bottom: 36rpx;
    display: flex;
    align-items: center;
    
    .label {
      font-size: 30rpx;
      color: #222;
      margin-right: 12rpx;
    }
    
    .value {
      font-size: 44rpx;
      color: #07c160;
      font-weight: bold;
      display: flex;
      align-items: center;
      &::before {
        content: '';
        display: inline-block;
        width: 36rpx;
        height: 36rpx;
        background: url('/static/vip/icon-beans.png') no-repeat center/cover;
        margin-right: 8rpx;
      }
    }
  }
  
  .card-group {
    margin-bottom: 36rpx;
    
    .group-header {
      display: flex;
      align-items: center;
      margin-bottom: 18rpx;
      
      .title {
        font-size: 32rpx;
        color: #222;
        font-weight: bold;
      }
      
      .tag {
        margin-left: 18rpx;
        padding: 4rpx 18rpx;
        background: #faad14;
        border-radius: 20rpx;
        font-size: 24rpx;
        color: #fff;
        
        &.buy {
          background: #ff6b6b;
        }
      }
    }
    
    .card-wrapper {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      gap: 0;
      margin-bottom: 32rpx;
      
      .vip-card {
        position: relative;
        background: #fff;
        border-radius: 20rpx;
        box-shadow: 0 4rpx 16rpx rgba(7,193,96,0.08);
        border: 2rpx solid #f0f0f0;
        padding: 48rpx 0 32rpx 0;
        margin-bottom: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 30%;
        min-width: 200rpx;
        max-width: 240rpx;
        margin-right: 3.333%;
        box-sizing: border-box;
        transition: box-shadow 0.2s, border-color 0.2s;

        &:nth-child(3n) {
          margin-right: 0;
        }

        &.exchange {
          border-color: #faad14;
        }
        &.purchase {
          border-color: #07c160;
        }
        
        .card-icon {
          position: absolute;
          top: -28rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 48rpx;
          height: 48rpx;
          background: #fff;
          border-radius: 50%;
          box-shadow: 0 2rpx 8rpx rgba(7,193,96,0.10);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 2;
          image {
            width: 32rpx;
            height: 32rpx;
          }
        }
        
        .card-content {
          margin-top: 24rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          width: 100%;
          
          .duration {
            font-size: 30rpx;
            color: #222;
            font-weight: bold;
            margin-bottom: 6rpx;
            letter-spacing: 1rpx;
            text-align: center;
          }
          
          .price {
            font-size: 28rpx;
            color: #faad14;
            font-weight: bold;
            margin-bottom: 6rpx;
            text-align: center;
          }
          
          .stock {
            font-size: 22rpx;
            color: #888;
            margin-bottom: 10rpx;
            text-align: center;
          }
          
          .exchange-btn,
          .purchase-btn {
            width: 90%;
            padding: 14rpx 0;
            background: linear-gradient(90deg, #07c160 0%, #34d399 100%);
            border-radius: 30rpx;
            font-size: 26rpx;
            color: #fff;
            margin-top: 10rpx;
            font-weight: 500;
            border: none;
            box-shadow: 0 2rpx 8rpx rgba(7,193,96,0.10);
            transition: background 0.2s;
            text-align: center;
            &.disabled {
              background: #ddd;
              color: #aaa;
              cursor: not-allowed;
            }
          }
        }
      }
    }
  }
  
  .vip-benefits {
    background: #f8f8f8;
    padding: 30rpx;
    border-radius: 16rpx;
    margin-top: 36rpx;
    
    .benefits-header {
      font-size: 32rpx;
      color: #222;
      font-weight: bold;
      margin-bottom: 20rpx;
    }
    
    .benefits-list {
      display: flex;
      flex-wrap: wrap;
      gap: 24rpx;
      
      .benefit-item {
        display: flex;
        align-items: center;
        gap: 12rpx;
        
        .icon {
          width: 44rpx;
          height: 44rpx;
        }
        
        .text {
          font-size: 28rpx;
          color: #222;
        }
      }
    }
  }
}
</style>